import axios from 'axios'
import { Message } from 'element-ui';


//响应的拦截器
axios.interceptors.response.use(success=>{
    //data：是指接收后台传来的json字符串数据RespBean（status,mag,obj）
    if (success.status && success.status == 200 && success.data.status == 500) {
        Message.error({message:success.data.msg});
        return;
    }
    if(success.data.msg) {
        Message.success({message:success.data.msg});
    }
    return success.data;
},error => {
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message:'服务器被吃了( ╯□╰ )'})
    }else if (error.response.status == 403) {
        Message.error({message:'权限不足，请联系管理员！'})
    }else if (error.response.status == 401) {
        Message.error({message:'尚未登录，请登录'})
    } else {
        if (error.response.data.msg) {
            Message.error({message:error.response.data.msg})
        } else {
            Message.error({message:'未知错误'})
        }
    }
    return;
})


//封装请求
//base:给每个url加个前缀。修改方便
let base = '';

//springSecurity默认只支持key-value传参，不能用json(默认不支持)
//登录用key-value传参
//url：``:是1前面的那个符号，不是单引号。代表变量
//若只写data:params,不写下面的transformrequest,则默认是json进行传参
//支持post进行key=value的传参
export const postKeyValueRequest=(url,params)=>{
    return axios({
        method:'post',
        url:`${base}${url}`,
        data:params,
        //定义传值方式为key=value的方式
        transformRequest:[function (data) {
            let ret = '';
            for (let i in data) {
                console.log(i);
                ret+=encodeURIComponent(i)+'='+encodeURIComponent(data[i])+'&'
            }
            return ret;
        }],
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    });
}

//支持post请求的json传值
export const postRequest=(url,params)=>{
    return axios({
        method:'post',
        url:`${base}${url}`,
        data:params
    })
}

//支持put请求的json传值
export const putRequest=(url,params)=>{
    return axios({
        method:'put',
        url:`${base}${url}`,
        data:params
    })
}

//支持delete请求的json传值
export const deleteRequest=(url,params)=>{
    return axios({
        method:'delete',
        url:`${base}${url}`,
        data:params
    })
}

//支持get请求的json传值
export const getRequest=(url,params)=>{
    return axios({
        method:'get',
        url:`${base}${url}`,
        data:params
    })
}



